require 'json'

COURSE_CODE_RE = /([^0-9]+)(\d*[A-Z]?)/
####################
# TSEs
####################

TECH = ARGV[0]
CSE = ARGV[1]
$id = 1

def load_tech_electives

    jsonData = IO.read(TECH)

    # Parse string
    j = JSON.parse(jsonData)

    # store objects in database
    output = j.collect do |course|
      dept, code = course["course_code"].match(COURSE_CODE_RE).captures

      c = {
        :id => $id,
        :department => dept,
        :course_code => code,
        :full_name =>  course["course_name"],
        :te_engdes => course["engdes"],
        :te_engsci => course["engsci"],
        :te_math => course["math"],
        :te_sci => course["sci"]
      }
      $id += 1
      c
    end

    return output
end

####################
# CSEs
####################

def load_cses

    jsonData = IO.read(CSE)

    # Parse string
    j = JSON.parse(jsonData)

    cse_categories = ['a','b','c','d']

    output = []

    cse_categories.each do |category|
        weight_key = "cse_#{category}".to_sym
        j[category].each do |course|
            dept, code = course["course_code"].match(COURSE_CODE_RE).captures
            weight = course["weight"]
            name = course["course_name"]

            c = {
                :id => $id,
                :department => dept,
                :course_code => code,
                :full_name => name,
                weight_key => weight
            }
            $id += 1

            output << c
        end
    end

    return output
end

courses = load_tech_electives
cousrses = courses.concat(load_cses)

courses.each do |c|
  puts "Course.create_or_update(#{c.inspect})"
end
